package formal.hash;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author DengYuan2
 * @create 2021-01-30 21:18
 */
public class E_594 {
    public static void main(String[] args) {
//        int[] a = {1, 3, 2, 2, 5, 2, 3, 7};
        int[] a = {1,1,1,1};
        System.out.println(findLHS(a));
    }

    /**
     * 我的写法-有些多余的地方
     * @param nums
     * @return
     */
    public static int findLHS(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>(nums.length);
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            int val = nums[i];
            map.put(val, map.getOrDefault(val, 0) + 1);
        }
        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> next = iterator.next();
            Integer key = next.getKey();
            Integer value = next.getValue();
            int plus=Math.max(map.getOrDefault(key - 1, 0), map.getOrDefault(key + 1, 0));
            if (plus!=0){

                max = Math.max(max, value + plus);
            }
        }
        return max;
    }

    /**
     * 大神写法
     * @param nums
     * @return
     */
    public static int findLHS2(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>(nums.length);
        int max =0;
        for (int num:nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }
        for (int key:map.keySet()){
            if (map.containsKey(key+1)){
                max=Math.max(max,map.get(key+1)+map.get(key));
            }
        }

        return max;
    }
}
